#!/bin/sh
#
# Script to generate the vls.g and vslTree.g grammar
# and then build the java source code.
#

# function usage
function usage {
echo "Usage: vsl.sh [<options>] [<argument> ...]
Generate the vsl and vslTree grammar and then compile the java source code files.

  -c, --clean         Clean up the source code folder.
      --no-vsl        Don't generate the vsl.g grammar.
      --no-vslTree    Don't generate the vslTree.g grammar. Implies --no-vsl.
      --run-test      Run all tests files or those provided as arguments.
                      (Generate and compile vsl grammar before if necessary).
  -h, --help          Display this message.

Please report any bug to <simon.maxime@gmail.com>."
}

# cd to the source folder
# (It should work if you are in the project root or at most in a sub-directory.)
function cdSrc {
    if test -d ../src
    then
        cd ../src
    elif test -d ./src
    then
        cd ./src
    else
        echo "Hey man, WTF?"
        exit 1;
    fi
}

# function clean
function clean {
    cdSrc

    echo "Cleaning up the source code folder..."
    rm -f *.class *.tokens vslTree.java vslParser.java vslLexer.java &&
    rm -rf ../nachos/test/* &&
    echo "done."
}

# function runTest
function runTest {
    cdSrc

    # If Vsl.class doesn't exist we cannot run the tests.
    if [ ! -e Vsl.class ]
    then
        build
        echo
    fi

    echo "Run tests..."

    if test "$#" -eq 0
    then
        python ../script/tests.py
    else
        echo
        python ../script/tests.py $*
    fi

    echo "done."
}

# function build
function build {
    cdSrc

    if test "$1" != "no-vslTree"
    then
        if test "$1" != "no-vsl"
        then
            echo "Generating vsl.g Grammar..."
            ../script/generate.sh vsl.g &&
            echo "done."
            echo
        fi
        echo "Generating vslTree.g Grammar..."
        ../script/generate.sh vslTree.g &&
        echo "done."
        echo
    fi

    echo "Building the java source code..."
    ../script/make.sh &&
    echo "done."
}

# Main program
case "$1" in
    -h|--help)
        usage
        exit 0
        ;;
    -c|--clean)
        clean
        exit 0
        ;;
    --run-test|--run-tests)
        shift
        runTest "$*"
        exit 0
        ;;
    --no-vsl)
        build no-vsl
        exit 0
        ;;
    --no-vslTree)
        build no-vslTree
        exit 0
        ;;
    "")
        build
        exit 0
        ;;
    *)
        usage
        exit 2
        ;;
esac
